package com.example.demo.auth;

import com.example.demo.dao.SysPermissionDao;
import com.example.demo.entity.SysPermission;
import com.example.demo.entity.SysUser;
import com.example.demo.service.SysPermissionService;
import com.example.demo.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

//用户登录校验逻辑
@Service()
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    SysUserService sysUserService;

    @Resource
    SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //从Db中判断用户是否存在
        SysUser user = sysUserService.getUserbyName(s);
        if(user==null){
            throw new RuntimeException("用户不存在");
        }else {
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            System.out.println("获取权限");
            //从Db中加载用户权限
            List<SysPermission> permissions = sysPermissionService.getPermissionByUid(user.getId());
            permissions.forEach(sysPermission -> {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode());
                grantedAuthorities.add(grantedAuthority);
            });
            //返回用户的信息。
            return new User(user.getAccount(),user.getPassword(),user.getEnabled(),user.getNotExpired(),user.getCredentialsNotExpired(),user.getAccountNotLocked(),grantedAuthorities);
        }


    }
}
